import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from '../../../widgets/one-operation/one-operation.component';
import {Router, ActivatedRoute} from '@angular/router';
import {TableUtil} from '../../../util/table-util';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgConstants} from '../../../constants/constants';
import {MsgResult} from '../../../models/msg-result';
import {SiteManageService} from './site-manage.service';
import {SiteV2API} from '../site-v2-constants';
import {DataDictionaryService} from '../../../services/dataDictionary.service';

declare var $;

@Component({
  selector: 'app-site-manage',
  templateUrl: './site-manage.component.html',
  styleUrls: ['./site-manage.component.css']
})
export class SiteManageComponent implements OnInit {
  proxy = {
    'siteManageAdd': () => this.siteAdd(),
    'siteManageUpdate': () => this.siteUpdate(),
    'siteManageDelete': () => this.siteDelete()
  };
  proxyDevice = {
    'assignDevice': () => this.assignDevice(),
    'deleteAssignSite': () => this.deleteAssignSite()
  };
  proxySiteRange = {
    'siteRangeAdd': () => this.siteRangeAdd(),
    'siteRangeUpdate': () => this.siteRangeUpdate(),
    'deleteSiteRange': () => this.deleteSiteRange()
  };
  siteId: string;

  siteCode: string;

  categorys: object;

  table;
  siteDeviceTable;
  rangeTable;

  searchSiteCode: string;
  searchSiteRegion: string;
  searchSiteName: string;
  isMove: string;

  siteContentType = 'site';
  siteContentArr: Array<any> = [
    {name: '设备', value: 'site'},
    {name: '站点区间信息', value: 'range'}
  ];

  // 数据字典中获取数据的编码
  dicPolluteType = 'ZDLEWRY';
  dicPolluteArr: Array<any> = [];

  airTypeCode = 'ZDKQLX';
  airTypeArr: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private sitesService: SiteManageService,
    private responseUtil: ResponseUtil,
    private dicService: DataDictionaryService,
    private pageSubject: PageSubject
  ) { }

  ngOnInit() {
    this.pushPage();
    this.loadSite();
    this.getDicAirType();
    this.loadSiteMonitor();
    this.loadSiteRange();
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    const path = new Path('设备监测', null);
    this.pageSubject.pushPage('站点管理', '查询', path);
  }

  /**
   * 初始化站点类型
   */
  initSiteCategory() {
    this.sitesService.getSiteCategoryInfos().subscribe(
      result => this.responseUtil.success(result , this.processSiteCategoryResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteCategoryResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      result.data.forEach( (val) => {
        this.dicPolluteArr.every((dic) => {
          if (val.monitorCategory === dic.value) {
            val.cateName = dic.display;
            return false;
          } else {
            return true;
          }
        })
      });
      this.categorys = result.data;
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  // 搜索
  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 站点查询
   */
  loadSite() {
    this.table = this.tableUtil.load('one_table_site', {
      columns: [
        { radio: true },
        { field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        { field: 'siteName', title: '站点名称', align: 'left'},
        { field: 'siteCode', title: '站点编码', align: 'left'},
        // { field: 'snCode', title: '设备编号', align: 'left'},
        { field: 'siteTypeName', title: '站点类型', align: 'left'},
        { field: 'regionName', title: '行政区划' , align: 'left'},
        { field: 'address', title: '站点位置' , align: 'left'},
        { field: 'isThied', title: '第三方' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'isMove', title: '移动设备' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'isUse', title: '启用' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'createDate', title: '创建时间' , align: 'left' , sortName: 'CREATEDATE', sortable: true, visible:  false}
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 10,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: true, //  单选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_sites',
      url: SiteV2API.sitePageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.siteName = $('#siteName').val();
        params.siteTypeCode = $('#monitor_add_siteTypeCode').val();
        params.isMove = $('#monitor_add_isMove').val();
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
          result.data.rows.forEach( (value, i) => {
            if (i === 0) {
              this.searchSiteCode = value.siteCode;
              this.searchSiteName = value.siteName;
              this.searchSiteRegion = value.regionCode;
              this.isMove = value.isMove;
            }
            value.createDate = value.createDate || '';
          });
        });
      },
      height: 500, // table高度
      sortable: true,
      sortOrder: 'desc',
      order: 'desc',
      sortName: 'CREATE_DATE',
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      showExport: true,       // 是否显示导出按钮
      exportDataType: 'all', // 导出类型
      buttonsAlign: 'right',  // 按钮位置
      exportTypes: ['excel'],  // 导出文件类型
      exportOptions: {
        ignoreColumn: [0],  // 根据索引忽[0,1,2]略某一列的导出数据
        fileName: '站点数据报表',  // 保存文件名称设置
        worksheetName: 'sheet1',  // 表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],

      },
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true, // 响应式
      undefinedText: '-',
      onLoadSuccess: (data) => {
        if (data.rows.length > 0) {
          this.table.bootstrapTable('check', 0);
          this.siteContentType = 'site';
          this.disabledRangeBtn();
        }
      },
      onCheck: (row) => {
        this.searchSiteCode = row.siteCode;
        this.searchSiteName = row.siteName;
        this.searchSiteRegion = row.regionCode;
        this.isMove = row.isMove;
        this.siteDeviceTable.bootstrapTable('refresh');
        this.rangeTable.bootstrapTable('refresh');
        this.disabledRangeBtn();
      }
    });
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat = (value, row, index) => {
    if (value === '0') {
      return '否';
    }
    if (value === '1') {
      return '是';
    }
  };

  /**
   * 删除站点操作
   */
  private siteDelete() {
    const rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo('请选择一条数据!');
    }
    this.siteId = this.tableUtil.getId(rows[0]);
    this.siteCode = this.tableUtil.getCloumn(rows[0], 'siteCode');

    if (!this.siteId || !this.siteCode) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', this.requestDelete);
    }
  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    // 调用后端接口
    if (!!this.siteId && !!this.siteCode) {
      this.sitesService.deleteSite(this.siteId, this.siteCode).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }
  };

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 站点添加
   */
  private siteAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 站点修改
   */
  private siteUpdate() {
    const rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo('请选择一条数据');
    }
    this.siteId = this.tableUtil.getId(rows[0]);
    if (!!this.siteId) {
      this.router.navigate(['update', {siteId: this.siteId}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据');
    }
  }

  /**
   * 为站点绑定设备
   */
  public assignDevice() {
    if (!!this.searchSiteCode) {
      this.router.navigate(['assign', {id: this.searchSiteCode, siteName: this.searchSiteName}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据!');
    }
  }

  /**
   * 改变
   */
  changeTab () {
    // this.siteContentType = value;
    this.siteDeviceTable.bootstrapTable('resetView');
    this.rangeTable.bootstrapTable('resetView');
    this.disabledRangeBtn();
  }
  /**
   * 设备查询
   */
  loadSiteMonitor() {
    this.siteDeviceTable = this.tableUtil.load('one_table_device', {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        // {field: 'siteCode', title: '站点代码', align: 'left', visible: false, switchable: false},
        // {field: 'siteName', title: '站点名称', align: 'left', class: 'one-table-col-2'},
        {field: 'snCode', title: '设备编号', align: 'left', class: 'one-table-col-2'},
        {field: 'monitorName', title: '设备类型', align: 'left', class: 'one-table-col-4'},
        {field: 'mPhone', title: '手机号', align: 'right', visible: false, class: 'one-table-col-2'},
        { field: 'ccid' , title: 'CCID', align: 'left' , class: 'one-table-col-2'},
        {field: 'receiveTimeMonitor', title: '数据接收时间', align: 'left', class: 'one-table-col-icon-6',
          sortName: 'RECEIVETIME', sortable: true},
        {field: 'receiveTimeStatus', title: '设备接收时间', align: 'left', class: 'one-table-col-icon-6',
          sortName: 'RECEIVETIME_DEV', sortable: true},
        {field: 'clientipinfClient', title: '客户端地址', align: 'left', class: 'one-table-col-2'},
        {field: 'clientipinfServer', title: '服务端地址', align: 'left', class: 'one-table-col-2', visible:  false},
        {field: 'clientipinfTranster', title: '下发通讯地址', align: 'left', class: 'one-table-col-2', visible: false},
        {field: 'statusUse', title: '使用状态', align: 'left', class: 'one-table-col-2', formatter: this.statusUseFormat},
        {field: 'statusWork', title: '运行状态', align: 'left', class: 'one-table-col-2', formatter: this.statusWorkFormat},
        // { field: 'remark',title:'说明' ,align:'left'},
        {field: 'transMode', title: '数据传输方式', align: 'left', class: 'one-table-col-6', formatter: this.dataTypeFormat},
        {field: 'createDate', title: '创建日期', align: 'left', class: 'one-table-col-2',
          sortName: 'CREATE_DATE', sortable: true , visible: false},
        {field: 'updateDate', title: '修改日期', align: 'left', class: 'one-table-col-2',
          visible: false, sortName: 'UPDATE_DATE', sortable: true },
      ],
      idField: 'id',
      // sidePagination: 'server',
      pagination: false,
      undefinedText: '-',
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: true, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_device',
      url: SiteV2API.getDevBySiteCode,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.siteCodes = this.searchSiteCode;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        if (result.data && result.data.length > 0) {
          return result.data
        } else {
          return [];
        }
      },
      height: 400, // table高度
      sortable: true,
      order: 'DESC',
      sortName: 'UPDATE_DATE',
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      // showExport: true,       // 是否显示导出按钮
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true// 响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }
  /**
   * 加载表格
   */
  loadSiteRange() {
    this.rangeTable = this.tableUtil.load('one_table_range',  {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        // {field: 'siteName', title: '站点名称', align: 'left'},
        // {field: 'siteCode', title: '站点编码', align: 'left'},
        {field: 'regionName', title: '行政区划', align: 'left'},
        {field: 'rangeName', title: '区间名称', align: 'left'},
        {field: 'startDate', title: '开始时间',  align: 'middle'},
        {field: 'endDate', title: '结束时间',  align: 'middle'},
        {field: 'modeType', title: '类型',  align: 'middle', formatter: this.modeTypeFormat},
        {field: 'airType', title: '空气数据源',  align: 'middle', formatter: this.airTypeFormat},
        {field: 'address', title: '位置',  align: 'middle'},
        {field: 'longitude', title: '定点经度',  align: 'middle'},
        {field: 'latitude', title: '定点纬度',  align: 'middle'},
        {field: 'isUse', title: '启用', align: 'middle', formatter: this.yesOrNoFormat},
        {field: 'remark', title: '说明', align: 'middle'}
      ],
      idField: 'id',
      // sidePagination: 'server',
      pagination: false,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_range',
      url: SiteV2API.getAllSiteRange,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.siteCode = this.searchSiteCode;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        if (result.data && result.data.length > 0) {
          return result.data
        } else {
          return [];
        }
      },
      height: 400, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true, // 响应式
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      undefinedText: '-',
    });
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private statusWorkFormat = (value, row, index) => {
    if (value === '1') {
      return '正常';
    }
    if (value === '2') {
      return '故障';
    }
    if (value === '3') {
      return '停用';
    }
  };
  private dataTypeFormat = (value, row, index) => {
    if (value === '1') {
      return 'gprs';
    }
    if (value === '2') {
      return 'lora';
    }
    if (value === '3') {
      return 'nb';
    }
  };
  private statusUseFormat = (value, row, index) => {
    if (value === '0') {
      return '测试';
    }
    if (value === '1') {
      return '正式';
    }
  };
  private modeTypeFormat = (value, row, index) => {
    if (value === '1') {
      return '巡航';
    }
    if (value === '0') {
      return '定点';
    }
  };
  private airTypeFormat = (value, row, index) => {
    let airType = '';
    this.airTypeArr.every((val) => {
      if (val.value === value) {
        airType = val.display;
        return false;
      } else {
        return true;
      }
    });
    return airType;
  };

  /**
   * 禁用rangeTable按钮
   */
  disabledRangeBtn = () => {
    const btn = $('#one_operation_range .btn');
    if (!(this.siteContentType === 'range' && (this.isMove === '1'))) {
      btn.map((i, elem) => {
        $(elem).prop('disabled', true);
      })
    } else {
      btn.map((i, elem) => {
        $(elem).prop('disabled', false);
      })
    }
  };
  /**
   * 获取数据字典中空气质量数据源
   */
  getDicAirType () {
    this.dicService.getChildDicByCode(this.airTypeCode).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.airTypeArr = result.data;
          }
          this.getDicPolluteType();
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 解除绑定设备
   */
  deleteAssignSite () {
    const rows = this.siteDeviceTable.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo('请选择一条数据!');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', () => {
        this.requestDeleteAssign(rows[0]);
      });
    }
  }
  requestDeleteAssign = (rowData) => {
    rowData.siteCode = '';
    rowData.updateDate = null;
    rowData.createDate = null;
    rowData.receiveTimeMonitor = null;
    rowData.clientipinfServer = null;
    rowData.receiveTimeStatus = null;
    rowData['0'] = null;
    rowData.RN = null;
    this.sitesService.siteMonitorEdit(rowData).subscribe(
      result => this.responseUtil.success(result, this.processSiteDeleteResult),
      error => this.responseUtil.error(error)
    )
  };
  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processSiteDeleteResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.siteDeviceTable.bootstrapTable('refresh');
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 站点区间信息添加
   */
  siteRangeAdd() {
    if (!!this.searchSiteCode) {
      this.router.navigate(['./rangeAdd', {siteCode: this.searchSiteCode, regionCode: this.searchSiteRegion}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据');
    }
  }

  /**
   * 站点区间信息修改
   */
  siteRangeUpdate() {
    const rows = this.rangeTable.bootstrapTable('getSelections');
    if (rows.length !== 1) {
      return this.dialogService.modalInfo('请选择一条数据!');
    }
    if (!!this.searchSiteCode) {
      this.router.navigate(['./rangeUpdate', {siteCode: this.searchSiteCode, siteRangeID: rows[0].id, regionCode: this.searchSiteRegion}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据');
    }
  }

  /**
   * 站点区间信息删除
   */
  deleteRange (id) {
    this.sitesService.deleteSiteRange(id).subscribe(
      result => this.responseUtil.success(result, this.processRangeDeleteResult),
      error => this.responseUtil.error(error)
    )
  }
  /**
   * 站点区间信息删除  -- 解除绑定设备
   */
  deleteSiteRange () {
    const rows = this.rangeTable.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo('请选择一条数据!');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', () => {
        this.requestDeleteRange(rows[0]);
      });
    }
  }
  requestDeleteRange = (rowData) => {
    rowData.siteCode = '';
    rowData.updateDate = null;
    rowData.createDate = null;
    rowData['0'] = null;
    rowData.RN = null;
    this.sitesService.updateSiteRange(rowData).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          this.rangeTable.bootstrapTable('refresh');
          this.deleteRange(rowData.id);
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    )
  };

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processRangeDeleteResult = (result: MsgResult) => {

  };
  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.dicPolluteType).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicPolluteArr = result.data;
            this.initSiteCategory();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
